package com.cuitrip.business.order.detail;

import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.widget.TextView;

import com.cuitrip.app.base.CtApiCallback;
import com.cuitrip.app.base.CtException;
import com.cuitrip.business.comment.CommentActivity;
import com.cuitrip.business.location.map.GaoDeMapActivity;
import com.cuitrip.business.login.LoginInstance;
import com.cuitrip.business.order.CancelOrderActivity;
import com.cuitrip.business.order.OrderCreateActivity;
import com.cuitrip.business.order.detail.event.OrderChangeEvent;
import com.cuitrip.business.order.detail.fetcher.OrderFetcher;
import com.cuitrip.business.order.detail.orderstatus.IOrderFetcher;
import com.cuitrip.business.order.detail.ui.IFinderOrderDetailView;
import com.cuitrip.business.order.detail.ui.ITravelerOrderDetailView;
import com.cuitrip.business.order.detail.ui.model.OrderCancelReasonRenderData;
import com.cuitrip.business.order.detail.ui.model.OrderInfoPartRenderData;
import com.cuitrip.business.order.detail.ui.model.PricePartRenderData;
import com.cuitrip.business.order.detail.ui.model.SimpleServicePartRenderData;
import com.cuitrip.business.order.detail.ui.present.FinderProxyPresent;
import com.cuitrip.business.order.detail.ui.present.IProxyPresent;
import com.cuitrip.business.order.detail.ui.present.TravelProxyPresent;
import com.cuitrip.business.order.detail.ui.viewholder.CancelReasonPartViewHolder;
import com.cuitrip.business.order.detail.ui.viewholder.OrderInfoPartViewHolder;
import com.cuitrip.business.order.detail.ui.viewholder.PricePartViewHolder;
import com.cuitrip.business.order.detail.ui.viewholder.SimpleServicePartViewHolder;
import com.cuitrip.business.order.detail.ui.viewholder.StubViewHolder;
import com.cuitrip.business.order.model.OrderItem;
import com.cuitrip.business.pay.PayOrderPageActivity;
import com.cuitrip.business.reminder.proxy.RemindProxy;
import com.cuitrip.business.setting.RelationActivity;
import com.cuitrip.component.choicedialog.ChoiceDialog;
import com.cuitrip.im.CtInfoNotificationMsgItemProvider;
import com.cuitrip.im.model.CTInformationNotificationMessage;
import com.cuitrip.im.proxy.CtRongInfoProxy;
import com.cuitrip.presenter.CommentPartRenderData;
import com.cuitrip.presenter.CommentPartViewHolder;
import com.cuitrip.service.R;
import com.cuitrip.util.ResourceUtil;
import com.cuitrip.util.time.InputTime;
import com.cuitrip.util.time.OutputTime;
import com.cuitrip.util.time.TimeUtil;
import com.cuitrip.util.track.TrackUtil;
import com.lab.app.BaseFragment;
import com.lab.rx.bus.RxBus;
import com.lab.utils.LogHelper;
import com.lab.utils.MessageUtils;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.functions.Action1;

/**
 * Created by baziii on 15/8/11.
 */
public class OrderFormFragment extends BaseFragment implements ITravelerOrderDetailView, IFinderOrderDetailView {

    public static final String TAG = "OrderFormFragment";
    public static final String ORDER_KEY = "OrderFormFragment.ORDER_KEY";
    public static final int REQUEST_CODE_MODIFY_ORDER = 1;
    MenuItem mOptionMenuItem;
    String mActionTitle;
    StubViewHolder<SimpleServicePartRenderData> mServiceStub = new StubViewHolder(new SimpleServicePartViewHolder());
    StubViewHolder<CommentPartRenderData> mCommentstub = new StubViewHolder(new CommentPartViewHolder());

    StubViewHolder<OrderInfoPartRenderData> mOrderInfoStub = new StubViewHolder(new OrderInfoPartViewHolder());
    StubViewHolder<PricePartRenderData> mPriceInfoStub = new StubViewHolder(new PricePartViewHolder());
    StubViewHolder<OrderCancelReasonRenderData> mCancelReasonInfoStub = new StubViewHolder(new CancelReasonPartViewHolder());
    @Bind(R.id.ct_service_info_v)
    ViewStub ctServiceInfoV;
    @Bind(R.id.ct_service_comment_v)
    ViewStub ctServiceCommentV;
    @Bind(R.id.ct_order_info_v)
    ViewStub ctOrderInfoV;
    @Bind(R.id.ct_price_info_v)
    ViewStub ctPriceInfoV;
    @Bind(R.id.ct_reason_info_v)
    ViewStub ctReasonInfoV;
    @Bind(R.id.ct_user_name_tv)
    TextView mItsNameTv;
    @Bind(R.id.ct_bottom_tv)
    TextView ctBottomTv;
    @Bind(R.id.ct_bottom_text)
    TextView ctBottomText;
    IProxyPresent baseOrderFormPresent;
    private IOrderFetcher mOrderFetcher;
    private OrderItem mOrderItem;

    public static OrderFormFragment newInstance(OrderItem orderItem) {
        Bundle args = new Bundle();
        args.putSerializable(ORDER_KEY, orderItem);
        OrderFormFragment fragment = new OrderFormFragment();
        fragment.setArguments(args);
        return fragment;
    }

    public void refresh(OrderItem orderItem) {
        getArguments().putSerializable(ORDER_KEY, orderItem);
        if (ctBottomTv != null) {
            renderWithData();
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.ct_order_form, menu);
        mOptionMenuItem = menu.findItem(R.id.action);
        super.onCreateOptionsMenu(menu, inflater);
    }

    @Override
    public void onPrepareOptionsMenu(Menu menu) {
        if (TextUtils.isEmpty(mActionTitle)) {
            mOptionMenuItem.setVisible(false);
        } else {
            mOptionMenuItem.setVisible(true);
            mOptionMenuItem.setTitle(mActionTitle);
        }
        super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action:
                baseOrderFormPresent.clickBottomText();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @OnClick(R.id.ct_bottom_tv)
    public void onBottomCLick() {
        baseOrderFormPresent.clickBottomAction();
    }

    @OnClick(R.id.ct_bottom_text)
    public void onBottomCLickText() {
        baseOrderFormPresent.clickBottomText();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.ct_order_form_order, null);
        ButterKnife.bind(this, view);
        buildModules();
        RxBus.getDefault().toObservable().subscribe(new Action1<Object>() {
            @Override
            public void call(Object o) {
                if (o instanceof OrderChangeEvent) {
                    if (getHostActivity() instanceof OrderFormActivity) {
                        refresh(((OrderFormActivity) getHostActivity()).mOrderItem);
                    }
                }

            }
        });
        return view;
    }

    @Override
    public void onDestroyView() {
        ButterKnife.unbind(this);
        super.onDestroyView();
    }

    private void buildModules() {
        mServiceStub.build(ctServiceInfoV);
        mCommentstub.build(ctServiceCommentV);
        mOrderInfoStub.build(ctOrderInfoV);
        mPriceInfoStub.build(ctPriceInfoV);
        mCancelReasonInfoStub.build(ctReasonInfoV);
    }

    private void renderModules(OrderMode orderMode) {
        mServiceStub.render(orderMode.getServiceData());
        mCommentstub.render(orderMode.getCommentData());
        mOrderInfoStub.render(orderMode.getOrderData());
        mPriceInfoStub.render(orderMode.getPricePartRenderData());
        mCancelReasonInfoStub.render(orderMode.getCancelReasonData());
    }

    public void renderWithData() {
        if (getArguments().containsKey(ORDER_KEY)) {
            mOrderItem = (OrderItem) getArguments().getSerializable(ORDER_KEY);
            boolean isImTravel = LoginInstance.getInstance().getUserInfo().isTravel();
            mOrderFetcher = new OrderFetcher(this);
            baseOrderFormPresent = isImTravel ? new TravelProxyPresent(this) : new FinderProxyPresent(this);
            requestPresentRender(mOrderItem);
        }
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        if (isAdded()) {
            renderWithData();
        }

    }

    @Override
    public void renderUi(OrderMode orderMode) {
        LogHelper.e("omg", "FinderOrderDetailView renderUi");
        renderModules(orderMode);
        renderBottom(orderMode);
        renderTopStatus();

    }

    private void renderTopStatus() {
        mItsNameTv.setText(buildItsname(this.mOrderItem));
    }


    private void renderBottom(OrderMode orderMode) {
        switch (orderMode.getBottomStyle()) {
            case NONE:
                ctBottomTv.setVisibility(View.GONE);
                break;
            case WHITE:
                ctBottomTv.setTextColor(ResourceUtil.getThemeColor());
                ctBottomTv.setBackgroundResource(ResourceUtil.getThemeWhiteButtonDrawableRes());
                break;
            case ORANGE:
                ctBottomTv.setTextColor(ResourceUtil.getColor(R.color.ct_white));
                ctBottomTv.setBackgroundResource(ResourceUtil.getThemeSolidButtonDrawableRes());
                break;
        }
        ctBottomTv.setText(orderMode.getBottomActionText());
        if (!TextUtils.isEmpty(orderMode.getBottomText())) {
            ctBottomText.setVisibility(View.VISIBLE);
            ctBottomText.setText(orderMode.getBottomText());
            ctBottomText.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG); //下划线
            ctBottomText.getPaint().setAntiAlias(true);
        } else {
            ctBottomText.setVisibility(View.GONE);
        }
    }

    @Override
    public void requestPresentRender(OrderItem orderItem) {
        baseOrderFormPresent.changeOrderItem(orderItem);
        baseOrderFormPresent.render();
    }


    @Override
    public void jumpModifyOrder(OrderItem orderItem) {
        OrderCreateActivity.startModify(getActivity(), orderItem);
    }

    @Override
    public void jumpPayOrder(OrderItem orderItem) {
        TrackUtil.trackScreenName("/pay");
        PayOrderPageActivity.startActivity(getActivity(), orderItem.getOid());
//        PayOrderPageActivity.startActivity(getActivity(),orderItem);
    }

    @Override
    public void jumpMapOrder(OrderItem orderItem) {
        try {
            double lat = Double.valueOf(orderItem.getLat());
            double lng = Double.valueOf(orderItem.getLng());
            GaoDeMapActivity.startShow(getActivity(), lat, lng, orderItem.getMeetingPlace());
        } catch (Exception e) {
            MessageUtils.showToast(R.string.feedback_data_err);
        }

    }

    @Override
    public void jumpCommentOrder(OrderItem orderItem) {
        CommentActivity.start(getActivity(), orderItem);
    }

    @Override
    public void jumpHelp(OrderItem orderItem) {
        RelationActivity.start(getActivity());
    }


    @Override
    public void jumpConfirmOrder(final OrderItem orderItem) {

        final ChoiceDialog dialog = new ChoiceDialog();
        dialog.setDialogTitleVisibility(false);
        dialog.setDialogMessage(getString(R.string.book_operation_accept_confirm));
        dialog.setDialogCoupleStyleSetting(getString(R.string.operation_yes), getString(R.string.operation_cancel), new ChoiceDialog.DialogStyleCoupleCallback() {
            @Override
            public boolean onPositiveButtonClick() {
                hideDialogFragment(dialog);
                showNoCancelDialog();
                mOrderFetcher.confirmOrder(orderItem, new CtApiCallback() {
                    @Override
                    public void onSuc() {
                        hideNoCancelDialog();
                        InputTime inputTime = InputTime.build(orderItem.getServiceDate(), TimeUtil.getZeroZone());


                        String formatDate = TimeUtil.formatTime(inputTime,
                                OutputTime.getInstance(OutputTime.OutputType.TYPE_COMMON_ENGLISH, TimeUtil.getZeroZone()));

                        CTInformationNotificationMessage message = CtRongInfoProxy.getInstance().getCommonOrderChangeMessage(CtInfoNotificationMsgItemProvider.CtParamKey.BOOK_MSG_CONFRIMED,
                                orderItem.getInsiderName(), inputTime.getTime(), formatDate);

                        CtRongInfoProxy.getInstance().sendSystemMessage(orderItem.getTargetId(), message, null);
                        getHostActivity().sendBroadcast(
                                new Intent(OrderItem.ORDER_STATUS_CHANGED_ACTION));
                    }

                    @Override
                    public void onFailed(CtException throwable) {
                        hideNoCancelDialog();
                        MessageUtils.showToast(throwable.getMessage());

                    }
                });
                return true;
            }

            @Override
            public boolean onNegativeButtonClick() {
                hideDialogFragment(dialog);
                return true;
            }
        });
        showDialogFragment(dialog);
    }

    @Override
    public void jumpCancelOrder(OrderItem orderItem) {
        if (LoginInstance.getInstance().getUserInfo().isTravel()) {
            TrackUtil.trackScreenName("/booking/summary/cancellation/" + mOrderItem.getStatus());
        } else {
            TrackUtil.trackScreenName("/insider/booking/summary/cancellation/" + mOrderItem.getStatus());
        }
        CancelOrderActivity.start(getHostActivity(), orderItem);

    }

    @Override
    public void jumpRefuseOrder(final OrderItem orderItem) {
        if (LoginInstance.getInstance().getUserInfo().isTravel()) {
            TrackUtil.trackScreenName("/booking/summary/cancellation/" + mOrderItem.getStatus());
        } else {
            TrackUtil.trackScreenName("/insider/booking/summary/cancellation/" + mOrderItem.getStatus());
        }
        CancelOrderActivity.start(getHostActivity(), orderItem);
    }

    @Override
    public void jumpStartOrder(final OrderItem orderItem) {
        final ChoiceDialog dialog = new ChoiceDialog();
        dialog.setDialogTitleVisibility(false);
        dialog.setDialogMessage(getString(R.string.trip_operation_start_confirm));
        dialog.setDialogCoupleStyleSetting(getString(R.string.operation_yes), getString(R.string.operation_cancel), new ChoiceDialog.DialogStyleCoupleCallback() {
            @Override
            public boolean onPositiveButtonClick() {
                dialog.dismiss();
                mOrderFetcher.startOrder(orderItem, new CtApiCallback() {
                    @Override
                    public void onSuc() {
                        hideNoCancelDialog();
                        getHostActivity().sendBroadcast(
                                new Intent(OrderItem.ORDER_STATUS_CHANGED_ACTION));
                    }

                    @Override
                    public void onFailed(CtException throwable) {
                        hideNoCancelDialog();
                        MessageUtils.showToast(throwable.getMessage());
                    }
                });
                return true;
            }

            @Override
            public boolean onNegativeButtonClick() {
                dialog.dismiss();
                return true;
            }
        });
        getHostActivity().showDialogFragment(dialog);
    }

    @Override
    public void jumpEndOrder(final OrderItem orderItem) {
        final ChoiceDialog dialog = new ChoiceDialog();
        dialog.setDialogTitleVisibility(false);
        dialog.setDialogMessage(getString(R.string.trip_operation_finish_confirm));
        dialog.setDialogCoupleStyleSetting(getString(R.string.operation_yes), getString(R.string.operation_cancel), new ChoiceDialog.DialogStyleCoupleCallback() {
            @Override
            public boolean onPositiveButtonClick() {
                dialog.dismiss();
                showNoCancelDialog();
                mOrderFetcher.endOrder(orderItem, new CtApiCallback() {
                    @Override
                    public void onSuc() {
                        hideNoCancelDialog();
                        ((OrderFormActivity) getActivity()).requestOrderDetail();
                        getHostActivity().sendBroadcast(
                                new Intent(OrderItem.ORDER_STATUS_CHANGED_ACTION));

                        RemindProxy.getInstance().endReminderDialog(getHostActivity(), orderItem);

                    }

                    @Override
                    public void onFailed(CtException throwable) {
                        hideNoCancelDialog();
                        MessageUtils.showToast(throwable.getMessage());

                    }
                });
                return true;
            }

            @Override
            public boolean onNegativeButtonClick() {
                dialog.dismiss();
                return true;
            }
        });
        getHostActivity().showDialogFragment(dialog);
    }


    public String buildItsname(OrderItem orderItem) {
        return SimpleServicePartRenderData.getStatusText(orderItem);
    }

    public void showLoading() {
        super.showLoading();
    }

    public void hideLoading() {
        super.hideLoading();
    }

}
